<?php
namespace Zxf5115\Laravel\Kernel\Traits;

use Exception;
use InvalidArgumentException;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Container\Container;
use Illuminate\Database\Eloquent\Model;
use Zxf5115\Laravel\Kernel\Utils\ReflectionUtil;

/**
 * @author zhangxiaofei [<1326336909@qq.com>]
 * @dateTime 2025-10-10
 *
 * 控制器公用特征类
 */
trait ControllerTrait
{
  /**
   * 默认查询条件
   */
  protected array $defaultWhere = [];

  /**
   * 允许客户端查询的字段
   */
  protected array $allowParams = [
    'organization_id',
    'category_id',
    'parent_id',
    'type',
    'name',
    'title',
    'username',
    'realname',
    'status',
    'create_time',
  ];

  /**
   * 关键字查询配置
   */
  protected array $allowKeywordParams = [
    'receive' => 'keyword',
    'match' => []
  ];

  /**
   * 关联查询配置
   */
  protected array $allowRelationParams = [];

  /**
   * 查询字段配置
   */
  protected array $fieldParams = [];

  /**
   * 排序规则
   */
  protected array $sortRules = [
    ['key' => 'create_time', 'value' => 'desc'],
    ['key' => 'id', 'value' => 'desc'],
  ];

  /**
   * 关联预加载配置
   */
  protected array $withRelations = [];

  /**
   * 过滤规则
   */
  protected array $filterRules = [];

  /**
   * 是否利用反射初始化模型类名
   */
  protected bool $resolveModel = true;

  /**
   * 逻辑处理初始化
   *
   * @param string $controllerClass 控制器类
   * @throws InvalidArgumentException 模型类不合法时抛出
   */
  public function resolveModelClass(string $controllerClass)
  {
    if($this->resolveModel)
    {
      // 如果没有modelClass
      if(empty($this->modelClass))
      {
        $this->modelClass = ReflectionUtil::resolveModelClass($controllerClass);
      }

      // 验证模型类合法性（避免无效模型）
      if (!class_exists($this->modelClass))
      {
        throw new InvalidArgumentException(
          sprintf('Class %s is not a valid Eloquent Model', $this->modelClass)
        );
      }
    }
  }

  /**
   * 获取分页列表
   *
   * @param Request $request 用户请求参数
   * @return JsonResponse 响应数据
   */
  public function list(Request $request) : JsonResponse
  {
    try
    {
      // 1. 参数验证
      $pageSize = empty($request->limit) ? 10 : intval($request->limit);

      // 2. 构建查询
      $response = $this->modelClass
                  ::whereBuild($this->getQueryFilterConfig(), $request->all())
                  ->withBuild($this->withRelations, __FUNCTION__)
                  ->order($this->sortRules)
                  ->fieldBuild($this->fieldParams, __FUNCTION__)
                  ->paging($pageSize);

      return success($response);
    }
    catch (Exception $e)
    {
      record($e);

      return error(__('kernel.request_failure'), 500);
    }
  }

  /**
   * 获取普通列表
   *
   * @param Request $request 用户请求参数
   * @return JsonResponse 响应数据
   */
  public function select(Request $request) : JsonResponse
  {
    try
    {
      // 1. 参数验证
      $limit = empty($request->limit) ? 1000 : intval($request->limit);

      // 2. 构建查询
      $response = $this->modelClass
                  ::whereBuild($this->getQueryFilterConfig(), $request->all())
                  ->withBuild($this->withRelations, __FUNCTION__)
                  ->limit($limit)
                  ->order($this->sortRules)
                  ->fieldBuild($this->fieldParams, __FUNCTION__)
                  ->get();

      return success($response);
    }
    catch (Exception $e)
    {
      record($e);

      return error(__('kernel.request_failure'), 500);
    }
  }

  /**
   * 获取单条数据
   *
   * @param Request $request 用户请求参数
   * @return JsonResponse 响应数据
   */
  public function data(Request $request) : JsonResponse
  {
    try
    {
      // 1. 构建查询
      $response = $this->modelClass
                  ::whereBuild($this->getQueryFilterConfig(), $request->all())
                  ->withBuild($this->withRelations, __FUNCTION__)
                  ->fieldBuild($this->fieldParams, __FUNCTION__)
                  ->first();

      return success($response);
    }
    catch (Exception $e)
    {
      record($e);

      return error(__('kernel.request_failure'), 500);
    }
  }

  /**
   * 数据详情数据
   *
   * @param Request $request 用户请求参数
   * @return JsonResponse 响应数据
   */
  public function view(Request $request, int $id) : JsonResponse
  {
    try
    {
      // 1. 构建查询
      $response = $this->modelClass
                  ::where(['id' => $id])
                  ->withBuild($this->withRelations, __FUNCTION__)
                  ->fieldBuild($this->fieldParams, __FUNCTION__)
                  ->first();

      return success($response);
    }
    catch (Exception $e)
    {
      record($e);

      return error(__('kernel.request_failure'), 500);
    }
  }

  /**
   * 设置数据状态
   *
   * @param Request $request 用户请求参数
   * @return JsonResponse 响应数据
   */
  public function status(Request $request) : JsonResponse
  {
    try
    {
      // 检查必要参数是否存在且不为空
      if(empty($request->id))
      {
        throw new InvalidArgumentException('Missing required parameters: id');
      }

      if(empty($request->field))
      {
        throw new InvalidArgumentException('Missing required parameters: field');
      }

      if(empty($request->value))
      {
        throw new InvalidArgumentException('Missing required parameters: value');
      }

      $field = $request->field;

      $model = $this->modelClass::find($request->id);
      $model->$field = intval($request->value);
      $model->save();

      return success(__('kernel.handle_success'));
    }
    catch (Exception $e)
    {
      record($e);

      return error(__('kernel.request_failure'), 500);
    }
  }

  /**
   * 删除数据
   *
   * @param Request $request 用户请求参数
   * @return JsonResponse 响应数据
   */
  public function delete(Request $request) : JsonResponse
  {
    try
    {
      // 检查必要参数是否存在且不为空
      if(empty($request->id))
      {
        throw new InvalidArgumentException('Missing required parameters: id');
      }

      $id = json_decode($request->id) ?? [0];

      $this->modelClass::whereIn('id', $id)->each(function ($query) {
        $query->delete();
      });

      return success(__('kernel.delete_success'));
    }
    catch (Exception $e)
    {
      record($e);

      return error(__('kernel.request_failure'), 500);
    }
  }

  /**
   * 初始化认证条件
   *
   * @return void
   */
  public function initializeAuthCondition(string $auth = 'api', array $params = []) : void
  {
    if(!empty(auth($auth)->user()) && !empty($params))
    {
      foreach($params as $field => $value)
      {
        $this->defaultWhere[$field] = auth($auth)->user()->$value;
      }
    }
  }

  /**
   * 获取查询参数配置信息
   *
   * @return array 参数配置数组，包含查询过滤相关的所有配置
   */
  public function getQueryFilterConfig() : array
  {
    return [
      'defaultWhere' => $this->defaultWhere,
      'allowParams' => $this->allowParams,
      'allowKeywordParams' => $this->allowKeywordParams,
      'allowRelationParams' => $this->allowRelationParams,
      'filterRules' => $this->filterRules ?: config('zxf5115.kernel.filter_rules')
    ];
  }
}
